package com.heima.comment.service.impl;

import com.heima.comment.dto.CommentRepayDto;
import com.heima.comment.dto.CommentRepayLikeDto;
import com.heima.comment.dto.CommentRepaySaveDto;
import com.heima.comment.entity.ApComment;
import com.heima.comment.entity.ApCommentRepay;
import com.heima.comment.entity.ApCommentRepayLike;
import com.heima.comment.entity.ApUser;
import com.heima.comment.feign.UserFeign;
import com.heima.comment.service.ICommentRepayService;
import com.heima.comment.vo.ApCommentRepayVo;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.MediaThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CommentRepayServiceImpl implements ICommentRepayService {

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 发表回复
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveRepay(CommentRepaySaveDto dto) {
        // 判断内容是否大于140字
        if (dto==null || dto.getContent().length()>=140){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        // 判断用户是否登录(要求使用手机号和密码登录的用户)
        User user = MediaThreadLocalUtil.get();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 安全过滤--阿里云文本审核
        boolean security = securityFiltering(dto.getContent());
        if (security==false){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 根据用户id查询用户,调用用户微服务提供的远程接口
        ApCommentRepay commentRepay=new ApCommentRepay();
        commentRepay.setAuthorId(user.getUserId());
        ResponseResult<ApUser> userById = userFeign.getUserById(user.getUserId());
        if (userById.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())){
            ApUser data = userById.getData();
            commentRepay.setAuthorName(data.getName());
        }
        commentRepay.setCommentId(dto.getCommentId());
        commentRepay.setContent(dto.getContent());
        commentRepay.setLikes(0);
        commentRepay.setCreatedTime(new Date());
        // 保存评论
        mongoTemplate.save(commentRepay);

       // 将评论表的回复数量+1
        Query query=new Query();
        query.addCriteria(Criteria.where("_id").is(dto.getCommentId()));
        Update update=new Update();
        update.inc("reply");
        mongoTemplate.updateFirst(query,update, ApComment.class);
        return ResponseResult.okResult();
    }

    /**
     * 点赞回复
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentRepayLikeDto dto) {
        //获取当前用户
        User user = MediaThreadLocalUtil.get();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 构建点赞记录
        ApCommentRepayLike like = new ApCommentRepayLike();
        like.setAuthorId(user.getUserId());
        like.setCommentRepayId(dto.getCommentRepayId());
        like.setOperation(dto.getOperation());
        //查询当前用户是否已经对文章点过赞
        Query query=new Query();
        query.addCriteria(Criteria.where("authorId").is(user.getUserId()));
        query.addCriteria(Criteria.where("commentRepayId").is(dto.getCommentRepayId()));
        ApCommentRepayLike one = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        //如果没有: 新增
        if (one==null){
            mongoTemplate.save(like);
            //更新回复列表的赞 +1
            Query commentQuery=new Query();
            commentQuery.addCriteria(Criteria.where("_id").is(dto.getCommentRepayId()));
            Update update=new Update();
            update.inc("likes");
            mongoTemplate.updateFirst(commentQuery,update,ApCommentRepay.class);
        }else {
            //如果没有,判断点赞还是取消
            if (one.getOperation() !=dto.getOperation()){
                int add=1;
                one.setOperation(dto.getOperation());
                mongoTemplate.save(one);
                //更新评论表的点赞数量
                if (dto.getOperation()==1){
                    add=-1;
                }
                Query commentQuery=new Query();
                commentQuery.addCriteria(Criteria.where("_id").is(dto.getCommentRepayId()));
                Update update=new Update();
                update.inc("likes");
                mongoTemplate.updateFirst(query,update,ApCommentRepay.class);
            }
        }
        return ResponseResult.okResult();
    }

    /**
     * 加载回复列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(CommentRepayDto dto) {
        //设置分页的数量为10
        if (dto.getSize()==null || dto.getSize()<=0 || dto.getSize()>=50){
            dto.setSize(10);
        }
        Query query=new Query();
        query.addCriteria(Criteria.where("commentId").is(dto.getCommentId()));
        query.addCriteria(Criteria.where("createdTime").lt(dto.getMinDate()));
        //分页 和 排序
        Pageable page = PageRequest.of(0, dto.getSize(), Sort.Direction.DESC, "createdTime");
        query.with(page);
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query, ApCommentRepay.class);
        //判断当前用户是否登录
        User user = MediaThreadLocalUtil.get();
            List<ApCommentRepayLike> likes = new ArrayList<>();
        if (user!=null){
            ArrayList<String> commentUIds = new ArrayList<>();
            for (ApCommentRepay apCommentRepay : apCommentRepays) {
                commentUIds.add(apCommentRepay.getId());
            }
            Query likeQuery=new Query();
            likeQuery.addCriteria(Criteria.where("authorId").is(user.getUserId()));
            likeQuery.addCriteria(Criteria.where("commentRepayId").in(commentUIds));
            likeQuery.addCriteria(Criteria.where("operation").is(0));
            likes = mongoTemplate.find(likeQuery, ApCommentRepayLike.class);
        }
        List<String> existCommentIds = new ArrayList<>();
        for (ApCommentRepayLike like : likes) {
            existCommentIds.add(like.getCommentRepayId());
        }
        // 返回vo对象集合
        List<ApCommentRepayVo> vos = new ArrayList<>();
        for (ApCommentRepay apComment : apCommentRepays) {
            ApCommentRepayVo vo = new ApCommentRepayVo();
            BeanUtils.copyProperties(apComment, vo);
            // 默认没有点赞,设置为1
            vo.setOperation(1);
            if (existCommentIds.contains(apComment.getId())) {
                vo.setOperation(0);
            }
            vos.add(vo);
        }
        return ResponseResult.okResult(vos);
    }


    /**
     * 安全过滤,阿里云文字审核
     * @param content
     * @return
     */
    private boolean securityFiltering(String content) {
        boolean result=false;
        try {
            Map map = greenTextScan.greenTextScan(content);
            String suggestion = (String) map.get("suggestion");
            switch (suggestion){
                case "pass":
                    result=true;
                    break;
                case "block":
                    result=false;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
